package com.upcode.weighing.config;

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;


import java.lang.reflect.Method;
import java.time.Duration;
import java.util.*;

/**
 * Redis 配置
 * @author 马涛
 * @date 2022/1/2
 */
@Configuration
@EnableCaching
public class RedisCacheConfig  {
    @Autowired
    private RedisConnectionFactory factory;

    @Bean("defaultKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return target.getClass().getName() + method.getName()+"["+ Arrays.asList(params).toString()+"]";
            }
        };
    }

    @Bean
    public CacheManager cacheManager() {
        // 生成一个默认配置，通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存的默认过期时间且设置不缓存空值
        config = config.entryTtl(Duration.ofDays(1)).disableCachingNullValues();

        // 设置一个初始化的缓存空间set集合
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("statistics");
        cacheNames.add("workerStatistics");
        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("statistics", config.entryTtl(Duration.ofDays(1)));
        configMap.put("workerStatistics", config.entryTtl(Duration.ofDays(1)));

        // 使用自定义的缓存配置初始化一个cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }


}
